#include <QPushButton>
#include "abstract-section-model.h"
#include "model-helper.h"
#include "sort-filter-proxy-model.h"
#include "table-data-addition-dialog.h"
#include "ui_table-data-addition-dialog.h"

TableDataAdditionDialog::TableDataAdditionDialog(QWidget *parent) :
    AbstractDataAdditionDialog(parent), ui(new Ui::TableDataAdditionDialog)
{
    ui->setupUi(this);
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    m_proxyModel = new SortFilterProxyModel(this);
    ui->tableView->setModel(m_proxyModel);
    ui->buttonBox->button(QDialogButtonBox::Ok)->setDisabled(true);
}

void TableDataAdditionDialog::setSectionInfo (const SectionInfo& sectionInfo)
{
    m_sectionInfo.setDatabaseClient(sectionInfo.databaseClient());
    m_sectionInfo.setLoadingParameters(sectionInfo.loadingParameters());
}

void TableDataAdditionDialog::initialize()
{
    m_proxyModel->setSourceModel(m_abstractModel);
    connect (ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
             this, SLOT(tableSelectionChanged()));
    m_abstractModel->setSectionInfo(m_sectionInfo);
    m_abstractModel->initialize();
    m_abstractModel->loadData();
}

void TableDataAdditionDialog::tableSelectionChanged()
{
    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(ui->tableView->selectionModel()->hasSelection());
}

void TableDataAdditionDialog::accept()
{
    QList<int> selectedRows = ModelHelper::normalSelectedRows(ui->tableView);
    QVariantList ids = m_abstractModel->ids(selectedRows);
    emit addDataRequested(ids);
    AbstractDataAdditionDialog::accept();
}
